package com.ruoyi.system.api.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ruoyi.common.config.Global;
import com.ruoyi.common.config.RedisConfig;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.api.ResponseWithData;
import com.ruoyi.system.api.domain.*;
import com.ruoyi.system.api.mapper.ReportInfoMapper;
import com.ruoyi.system.api.mapper.StReportPortMapper;
import com.ruoyi.system.api.service.IInterfaceOperationLogService;
import com.ruoyi.system.api.service.PokeRequestServe;
import com.ruoyi.system.api.service.SparePartsService;
import org.apache.commons.lang3.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import sun.misc.BASE64Encoder;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @ClassName SparePartsServiceImpl
 * @Description: TODO
 * @Author wlf
 * @Date 2020/3/2
 * @Version V1.0
 **/
@Service
public class SparePartsServiceImpl implements SparePartsService {

    private static final Logger log = LoggerFactory.getLogger(SparePartsServiceImpl.class);

    @Autowired
    private PokeRequestServe pokeRequestServe;

    @Autowired
    private ReportInfoMapper reportInfoMapper;

    /**
     * 设置accesstoken过期时间（秒）
     */
//    public static final int ACCESS_TOKEN_TIMES = 7200;

    /**
     * 配置文件
     */
    @Autowired
    private Global global;

    /**
     * redis配置文件
     */
    @Autowired
    private RedisConfig redisConfig;

    /**
     * 接口调用日志
     */
    @Autowired
    private IInterfaceOperationLogService iInterfaceOperationLogService;

    @Autowired
    private StReportPortMapper reportPortMapper;


    /**
     * 我的备件（没用）
     *
     * @param enginnerId
     * @param status
     * @param partNo
     * @param partName
     * @param custName
     * @return
     */
    @Override
    public ResponseWithData<?> queryPartByFseId(String enginnerId, String status, String partNo, String partName, String custName) {
        String ccServerUrl = global.getCcServerUrl();
        StringBuffer url = new StringBuffer();
        url.append(ccServerUrl);
        url.append("queryPartByFseId.asmx/queryPartByFseIdHandle?enginner_id=").append(enginnerId);
        url.append("&Status=").append(status);
        url.append("&Part_no=").append(partNo);
        url.append("&Part_name=").append(partName);
        url.append("&CustName=").append(custName);

        return pokeRequestServe.transGet(url.toString(), "获取工程师名下备件接口", "queryPartByFseId");
    }

    /**
     * 我的备件
     *
     * @param info
     * @return
     */
    @Override
    public ResponseWithData<?> queryPartByFseIdPost(PartInfo info) {
        String ccServerUrl = global.getCcServerUrl();
        StringBuffer url = new StringBuffer();
        url.append(ccServerUrl);
        url.append("queryPartByFseId.asmx/queryPartByFseIdHandle");


        StringBuffer param = new StringBuffer("enginner_id=").append(info.getEnginner_id() == null ? "" : info.getEnginner_id());
        param.append("&Status=").append(info.getStatus() == null ? "" : info.getStatus());
        param.append("&Part_no=").append(info.getPart_no() == null ? "" : info.getPart_no());
        param.append("&Part_name=").append(info.getPart_name() == null ? "" : info.getPart_name());
        param.append("&CustName=").append(info.getCustName() == null ? "" : info.getCustName());
        param.append("&Part_id=").append(info.getPart_id() == null ? "" : info.getPart_id());
        param.append("&Part_DebitNo=").append(info.getPart_DebitNo() == null ? "" : info.getPart_DebitNo());
        param.append("&istodo=").append(info.getIstodo() == null ? "" : info.getIstodo());

        return pokeRequestServe.transPost(url.toString(), "获取工程师名下备件接口", "queryPartByFseId", param.toString());
    }

    /**
     * 我的备件---2.74获取工程师转移备件列表接口
     * 里面包含了已转移过的备件，且可提交转移，需剔除，6月25日cc 增加接口
     * @param info
     * @return
     */
    @Override
    public ResponseWithData<?> queryPartByFseIdPost2(PartInfo info) {
        String ccServerUrl = global.getCcServerUrl();
        StringBuffer url = new StringBuffer();
        url.append(ccServerUrl);
        //url.append("queryPartByFseId.asmx/queryPartByFseIdHandle");
        url.append("queryChangePartByFseId.asmx/queryChangePartByFseIdHandle");

        StringBuffer param = new StringBuffer("enginner_id=").append(info.getEnginner_id());
        //param.append("&Status=").append(info.getStatus() == null ? "" : info.getStatus());
        param.append("&Part_no=").append(info.getPart_no() == null ? "" : info.getPart_no());
        param.append("&Part_name=").append(info.getPart_name() == null ? "" : info.getPart_name());
        param.append("&CustName=").append(info.getCustName() == null ? "" : info.getCustName());
        param.append("&Part_id=").append(info.getPart_id() == null ? "" : info.getPart_id());
        param.append("&Part_DebitNo=").append(info.getPart_DebitNo() == null ? "" : info.getPart_DebitNo());
        // param.append("&istodo=").append(info.getIstodo() == null ? "" : info.getIstodo());

        return pokeRequestServe.transPost(url.toString(), "2.74获取工程师转移备件列表接口", "queryPartByFseId", param.toString());
    }

    /**
     * 其他工程师备件
     *
     * @param params
     * @return
     */
    @Override
    public ResponseWithData<?> getPartInfoByCode(Map<String, Object> params) {
        String ccServerUrl = global.getCcServerUrl();
        StringBuffer url = new StringBuffer();
        url.append(ccServerUrl);
        url.append("getPartInfoByCode.asmx/getPartInfoByCodeHandle");
        StringBuffer postParam = new StringBuffer();

        postParam.append("&Part_code=").append(params.get("partCode") == null ? "" : params.get("partCode").toString());
        postParam.append("&enginner_name=").append(params.get("enginnerName") == null ? "" : params.get("enginnerName").toString());
      //  postParam.append("&enginner_id=").append(params.get("enginnerId") == null ? "" : params.get("enginnerId").toString());
//         postParam.append("&enginner_name=").append(params.get("enginnerName").toString());
//         postParam.append("&enginner_id=").append(params.get("enginnerId").toString());
//        postParam.append("&Status=").append(params.get("status").toString());
//        postParam.append("Part_code=").append("");
//        postParam.append("&enginner_name=").append("");
        postParam.append("&enginner_id=").append("");
        postParam.append("&Status=").append("5");
        ResponseWithData<?> responseWithData = pokeRequestServe.transPost(url.toString(), "获取其他工程师名下备件接口", "getPartInfoByCode", postParam.toString());
        JSONObject obj = null;
        if (!ObjectUtils.isEmpty(responseWithData.getData())) {
            obj = JSONObject.parseObject(responseWithData.getData().toString());
            JSONArray jsonArray = obj.getJSONArray("record");
            if (!ObjectUtils.isEmpty(jsonArray)) {
                for (Object object : jsonArray) {
                    JSONObject jsonObj = (JSONObject) object;
                    String FSEReceiveDate = jsonObj.getString("FSEReceiveDate");
                    String sendDate = jsonObj.getString("Send_time");
                    if (StringUtils.isEmpty(FSEReceiveDate)||StringUtils.isEmpty(sendDate)) {
                        jsonObj.put("days", "0");
                        continue;
                    }
                    //收货日期
                    LocalDateTime receiveDate = StringToDateTime(FSEReceiveDate);
                    //发货日期
                  //  LocalDateTime sendDatee = StringToDateTime(sendDate);
                    //当前时间
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    LocalDateTime curentTime=StringToDateTime(df.format(System.currentTimeMillis()));
                    java.time.Duration duration = java.time.Duration.between(receiveDate,curentTime);

                    String days = String.valueOf((duration.toDays()));
                    jsonObj.put("days", days);
                }
            }
        }
        return new ResponseWithData().success(obj).msg("success").code(200);
    }

    public LocalDateTime StringToDateTime(String str1) {
        // String str1="2018-07-05 12:24:12";
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime parse = LocalDateTime.parse(str1, dtf);
        return parse;
    }

    /**
     * 查物流
     *
     * @param logisticNo
     * @param shipercode
     * @param custname
     * @return
     */
    @Override
    public ResponseWithData<?> getLogisticsInfoByNumber(String logisticNo, String shipercode, String custname) {
        // 校验 物流公司参数
//        if (StringUtils.isNotBlank(shipercode)) {
//            物流公司取的接口字典，不需校验
//            String arr[] = {"SF", "EMS", "FEDEX", "MHKD", "STO", "YD", "ZTO", "JLDT", "XJ"};
//            int res = Arrays.binarySearch(arr, shipercode);
//            if (res < 0){
//                return new ResponseWithData().success().msg("参数错误 物流公司编码不符合要求").code(301);
//            }
//            if (shipercode.equals("SF")) {
//                if (null == custname || custname.trim().equals("")) {
//                    return new ResponseWithData().success().msg("参数错误 请输入参数工程师手机后4位").code(302);
//                }
//            }
//        }
        String ccServerUrl = global.getCcServerUrl();
        StringBuffer url = new StringBuffer();
        url.append(ccServerUrl);
        url.append("getLogisticsInfoByNumber.asmx/getLogisticsInfoByNumberHandle");
        StringBuffer postParam = new StringBuffer();
        postParam.append("shipercode=").append(shipercode);
        postParam.append("&Logistic_no=").append(StringUtils.isEmpty(logisticNo) ? "" : logisticNo);
        postParam.append("&CustName=").append(StringUtils.isEmpty(custname) ? "" : custname);

        return pokeRequestServe.transPost(url.toString(), "获取备件物流接口", "getLogisticsInfoByNumber", postParam.toString());
    }

    /**
     * 备件收货
     *
     * @param params
     * @return
     */
    @Override
    public ResponseWithData<?> partReceiving(Map<String, Object> params) {
        String ccServerUrl = global.getCcServerUrl();
        StringBuffer url = new StringBuffer();
        url.append(ccServerUrl);
        url.append("partReceiving.asmx/partReceivingHandle");
        StringBuffer postParam = new StringBuffer("");
        postParam.append("enginner_id=").append(params.get("enginner_id").toString());
        postParam.append("&Part_id=").append(params.get("Part_id").toString());
        postParam.append("&Remark=");
        if (null != params.get("Remark")) {
            postParam.append(params.get("Remark").toString());
        }

        return pokeRequestServe.transPost(url.toString(), "备件收货接口", "partReceiving", postParam.toString());
    }

    /**
     * 备件拆分
     *
     * @param params
     * @return
     */
    @Override
    public ResponseWithData<?> partSplit(Map<String, Object> params) {
        String ccServerUrl = global.getCcServerUrl();
        StringBuffer url = new StringBuffer();
        url.append(ccServerUrl);
        url.append("partSplit.asmx/partSplitHandle");
        StringBuffer postParam = new StringBuffer("");
        postParam.append("enginner_id=").append(params.get("enginner_id").toString());
        postParam.append("&Part_id=").append(params.get("Part_id").toString());

        return pokeRequestServe.transPost(url.toString(), "备件拆分接口", "partSplit", postParam.toString());
    }

    /**
     * 备件绑码
     *
     * @param params
     * @return
     */
    @Override
    public ResponseWithData<?> partBind(Map<String, Object> params) {
        String ccServerUrl = global.getCcServerUrl();
        StringBuffer url = new StringBuffer();
        url.append(ccServerUrl);
        url.append("partBind.asmx/partBindHandle");
        StringBuffer postParam = new StringBuffer("");
        postParam.append("enginner_id=").append(params.get("enginner_id").toString());
        postParam.append("&Part_id=").append(params.get("Part_id").toString());
        postParam.append("&Rebarcode=").append(params.get("Rebarcode").toString());

        return pokeRequestServe.transPost(url.toString(), "备件绑码接口", "partBind", postParam.toString());
    }

    /**
     * 备件借货(没用)
     *
     * @param spareParts
     * @return
     */
    @Override
    public ResponseWithData<?> partBorrowApply(SpareParts spareParts) {
        String ccServerUrl = global.getCcServerUrl();
        StringBuffer url = new StringBuffer();
        url.append(ccServerUrl);
        url.append("partBorrowApply.asmx/partBorrowApply").toString();

        return pokeRequestServe.transPost(url.toString(), "备件借货申请", "partBorrowApply", JSON.toJSONString(spareParts, SerializerFeature.WriteNullStringAsEmpty));
    }

    /**
     * 备件借货
     *
     * @param params
     * @return
     * @throws Exception
     */
    @Override
    public ResponseWithData<?> partBorrowApply(String params) throws Exception {
        String ccServerUrl = global.getCcServerUrl();
        StringBuffer url = new StringBuffer();
        url.append(ccServerUrl);
        url.append("partBorrowApply.asmx/partBorrowApplyHandle").toString();
        JSONObject obj = JSON.parseObject(params);
        
        String mainStr = URLDecoder.decode(obj.get("spareParts").toString(), "UTF-8");
        String arrStr = URLDecoder.decode(obj.get("partInfo").toString(), "UTF-8");
 //       arrStr = StringEscapeUtils.unescapeXml(StringEscapeUtils.escapeXml(arrStr));
        StringBuffer postParam = new StringBuffer("");
        if (org.apache.commons.lang3.StringUtils.isNotBlank(mainStr) && org.apache.commons.lang3.StringUtils.isNotBlank(arrStr)) {
            // 参数解析
            SpareParts spareParts = JSON.parseObject(mainStr, SpareParts.class);
            List<PartInfo> partList = JSON.parseArray(arrStr, PartInfo.class);
            String sparePartsStr = pokeRequestServe.spellPrams(spareParts);
            // 参数拼接
            postParam.append(sparePartsStr);
            postParam.append("&Part_info=").append(JSON.toJSONString(partList, SerializerFeature.WriteNullStringAsEmpty));
        } else {
            return new ResponseWithData().success().msg("error 缺少参数").code(203);
        }
        System.out.println(postParam);
        return pokeRequestServe.transPostNew(url.toString(), "备件借货申请", "partBorrowApply", postParam.toString());
    }

    /**
     * tl查询team下工程师市备件
     *
     * @param params
     * @return
     */
    public ResponseWithData<?> queryPartByTlId(Map<String, Object> params) {
        String ccServerUrl = global.getCcServerUrl();
        StringBuffer url = new StringBuffer();
        url.append(ccServerUrl);
        url.append("queryPartByTlId.asmx/queryPartByTlIdHandle");
        StringBuffer postParam = new StringBuffer();
        postParam.append("Part_no=").append(params.get("partCode").toString());
        postParam.append("&enginner_name=").append(params.get("enginnerName").toString());
        postParam.append("&tl_id=").append(params.get("enginnerId").toString());
        postParam.append("&Engineer_id=").append("");
       // postParam.append("&Engineer_id=").append(params.get("enginnerId").toString());
        postParam.append("&Status=").append(params.get("status").toString());


        return pokeRequestServe.transPost(url.toString(), "获取TL名下FSE备件接口", "queryPartByTlId", postParam.toString());
    }

    /**
     * 校验备件是否绑定草稿
     *
     * @param enginnerId
     * @param partIds
     * @return
     */
    @Override
    public ResponseWithData<?> queryPartDraft(String enginnerId, String partIds) {
        List<ReportInfo> list = reportInfoMapper.queryPartDraft(enginnerId, partIds);
        return new ResponseWithData().success(list).msg("success").code(200);
    }

    /**
     * 备件转移
     *
     * @param params
     * @return
     */
    @Override
    public ResponseWithData<?> partChangeHandle(String params) {
        String ccServerUrl = global.getCcServerUrl();
        StringBuffer url = new StringBuffer();
        url.append(ccServerUrl);
        url.append("partChange.asmx/partChangeHandle");

        StringBuffer postParam = new StringBuffer();
        JSONObject obj = JSON.parseObject(params);
        String enginner_id = obj.get("enginner_id").toString();
        String new_enginner_id = obj.get("new_enginner_id").toString();
        String Remark = obj.get("Remark").toString();
        String arrStr = obj.get("partInfo").toString();
        postParam.append("enginner_id=").append(enginner_id);
        postParam.append("&new_enginner_id=").append(new_enginner_id);
        postParam.append("&Remark=").append(Remark);
        postParam.append("&Part_info=").append(arrStr);

        return pokeRequestServe.transPost(url.toString(), "备件转移接口", "partChangeHandle", postParam.toString());
    }

    /**
     * 备件还库还货
     *
     * @param params
     * @return
     */
    @Override
    public ResponseWithData<?> partBindReturnHandle(String params) throws Exception {
        JSONObject obj = JSON.parseObject(params);
        String mainStr = obj.get("bindReturn").toString();
        String arrStr = obj.get("bindReturnPartInfo").toString();
        StringBuffer postParam = new StringBuffer("");
        if (org.apache.commons.lang3.StringUtils.isNotBlank(mainStr) && org.apache.commons.lang3.StringUtils.isNotBlank(arrStr)) {

            // 参数解析
            BindReturn bindReturn = JSON.parseObject(mainStr, BindReturn.class);
            List<BindReturnPartInfo> partList = JSON.parseArray(arrStr, BindReturnPartInfo.class);

            // 参数拼接（老方法不用了）
            // String sparePartsStr = pokeRequestServe.spellPrams(bindReturn);
            // postParam.append(sparePartsStr);

            // 申请内容参数
            postParam.append("enginner_id=").append(bindReturn.getEnginner_id() == null ? "" : bindReturn.getEnginner_id());
            postParam.append("&ReexpressNumber=").append(bindReturn.getReexpressNumber() == null ? "" : bindReturn.getReexpressNumber());
            postParam.append("&ReexpressCompany=").append(bindReturn.getReexpressCompany() == null ? "" : bindReturn.getReexpressCompany());
            postParam.append("&Transtype=").append(bindReturn.getTranstype() == null ? "" : bindReturn.getTranstype());
            postParam.append("&Province=").append(bindReturn.getReexpressNumber() == null ? "" : bindReturn.getProvince());
            postParam.append("&City=").append(bindReturn.getCity() == null ? "" : bindReturn.getCity());
            postParam.append("&address=").append(bindReturn.getAddress() == null ? "" : bindReturn.getAddress());
            postParam.append("&contactinfo=").append(bindReturn.getContactinfo() == null ? "" : bindReturn.getContactinfo());
            postParam.append("&weight=").append(bindReturn.getWeight() == null ? "" : bindReturn.getWeight());
            postParam.append("&Insure=").append(bindReturn.getInsure() == null ? "" : bindReturn.getInsure());
            postParam.append("&dept=").append(bindReturn.getDept() == null ? "" : bindReturn.getDept());
            postParam.append("&Remark=").append(bindReturn.getRemark() == null ? "" : bindReturn.getRemark());
            postParam.append("&ProDesc=").append(bindReturn.getProDesc() == null ? "" : bindReturn.getProDesc());

            // 图片路径及base64参数
            String doapicUrl = bindReturn.getDoa_pic();
            if (StringUtils.isNotEmpty(doapicUrl)) {
                // 图片地址
                // String webUrl = global.getPicUrl() + doapicUrl;
                // 图片名
                String fileName = "";
                if (doapicUrl.lastIndexOf("/") >= 0) {
                    fileName = doapicUrl.substring((doapicUrl.lastIndexOf("/") + 1), doapicUrl.length());
                    //System.out.println(fileName);
                }
                // 图片base64
                String path = global.getProfile() + doapicUrl;
                String s = getBase64(path);
                postParam.append("&Doa_pic=").append(fileName);
                postParam.append("&b=").append(s);
            } else {
                postParam.append("&b="); //必须得传
                postParam.append("&Doa_pic="); //必须得传
            }

            // 备件内容参数
            if (null != partList && partList.size() > 0) {
                String partStr = JSON.toJSONString(partList, SerializerFeature.WriteNullStringAsEmpty).replaceAll("Part_qty", "Part_ qty");
                postParam.append("&Part_info=").append(partStr); //当前接口有问题，只能传一个
            } else {
                postParam.append("&Part_info="); //必须得传
            }

        } else {
            return new ResponseWithData().success().msg("error 缺少参数").code(203);
        }

        System.out.println(postParam.toString());

        String ccServerUrl = global.getCcServerUrl();
        StringBuffer url = new StringBuffer();
        url.append(ccServerUrl);
        url.append("partBindReturn.asmx/partBindReturnHandle");

        return pokeRequestServe.transPost(url.toString(), "备件绑码还库接口", "partBindReturnHandle", postParam.toString());
    }

    @Override
    public ResponseWithData<?> consumablesList(String tableName, Long engineerId) {
        StringBuffer postParam = new StringBuffer();
        postParam.append("engineer_id=").append(engineerId);
        postParam.append("&last_sync_time=").append(System.currentTimeMillis() + "");
        postParam.append("&sync_table_name=").append(tableName);

        String ccServerUrl = global.getCcServerUrl();
        StringBuffer url = new StringBuffer();
        url.append(ccServerUrl);
        url.append("SyncTables.asmx/GetParamTables?output=json");

        return pokeRequestServe.transPost(url.toString(), "同步基础数据接口", "queryPartByTlId", postParam.toString());
    }

    @Override
    public ResponseWithData<?> QueryPriceByPartCode(Map<String, Object> params) {
        String ccServerUrl = global.getCcServerUrl();
        StringBuffer url = new StringBuffer();
        url.append(ccServerUrl);
        url.append("QueryPriceByPartCode.asmx/QueryPriceByPartCodeHandle");
        StringBuffer postParam = new StringBuffer();
        postParam.append("partcode=").append(params.get("partcode").toString());

        return pokeRequestServe.transPost(url.toString(), "备件号查询Price及备件名称接口", "QueryPriceByPartCode", postParam.toString());
    }

    /**
     * 图片转base64
     *
     * @return
     * @throws Exception
     */
    public String getBase64(String path) {
//        String path = "D:\\ruoyi\\uploadPath\\parts\\10049\\test\\1587026408.jpg";
        String imgFile = path;// 待处理的图片
        InputStream in = null;
        byte[] data = null;
        String encode = null; // 返回Base64编码过的字节数组字符串
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        try {
            // 读取图片字节数组
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            int count1 = in.read(data);
            encode = encoder.encode(data).replaceAll("\r\n", "");
            System.out.println(encode);
        } catch (IOException e) {
//            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                log.error("程序异常", e.getMessage());
            }
        }
        return encode;
    }

    @Override
    public ResponseWithData<?> ccAddressData() {
        StringBuffer postParam = new StringBuffer();
        postParam.append("engineer_id=");
        postParam.append("&last_sync_time=").append(System.currentTimeMillis() + "");
        postParam.append("&sync_table_name=").append("ProCity");

        String ccServerUrl = global.getCcServerUrl();
        StringBuffer url = new StringBuffer();
        url.append(ccServerUrl);
        url.append("SyncTables.asmx/GetParamTables?output=json");

        Map<String, String> result = pokeRequestServe.transPostJD(url.toString(), "同步基础数据接口——获取cc端省市区数据", "queryPartByTlId", postParam.toString());
        if (result.get("code").equals("200")) {
            JSONObject body = JSONObject.parseObject(result.get("responseBody"));
            if (body.getInteger("status") == 1) {
                JSONArray arr = body.getJSONArray("record");
                List<Object> provinceList = new ArrayList<>();
                List<Object> cityList = new ArrayList<>();
                List<Object> countyList = new ArrayList<>();
                String proId = ""; //省id
                String citId = ""; //市id
                Map<String, Object> provinceMap;
                Map<String, Object> cityMap;
                for (int i = 0; i < arr.size(); i++) {
                    JSONObject arrObj = arr.getJSONObject(i);

                    // 省数据
                    if (!arrObj.getString("PROVINCEID").equals(proId)) {
                        // 市数组清空
                        cityList = new ArrayList<>();
                        // 省id
                        proId = arrObj.getString("PROVINCEID");
                        // 省内容
                        provinceMap = new HashMap<>();
                        provinceMap.put("value", proId);
                        provinceMap.put("text", arrObj.getString("PROVINCE"));
                        provinceMap.put("children", cityList);
                        provinceList.add(provinceMap);
                    }

                    // 市数据
                    if (!arrObj.getString("CityID").equals(citId)) {
                        // 区县数组清空
                        countyList = new ArrayList<>();
                        // 市id
                        citId = arrObj.getString("CityID");
                        // 市内容
                        cityMap = new HashMap<>();
                        cityMap.put("value", citId);
                        cityMap.put("text", arrObj.getString("CITY"));
                        cityMap.put("children", countyList);
                        cityList.add(cityMap);
                    }

                    // 区县数据（过滤null值）
                    if (org.apache.commons.lang3.StringUtils.isNotEmpty(arrObj.getString("COUNTYID"))) {
                        // 区县内容
                        Map<String, String> county = new HashMap<>();
                        county.put("value", arrObj.getString("COUNTYID"));
                        county.put("text", arrObj.getString("COUNTY"));
                        countyList.add(county);
                    }
                }
                //System.out.println(JSONObject.toJSONString(provinceList));
                return new ResponseWithData().success(provinceList).msg("success").code(200);
            } else {
                return new ResponseWithData().success(body.getInteger("status")).msg(body.getString("message")).code(200);
            }
        } else {
            return new ResponseWithData().success().msg(result.get("msg")).code(Integer.parseInt(result.get("code")));
        }
    }

    @Override
    public ResponseWithData<?> checkTodayIsOnjobInfo() {
        String ccServerUrl = global.getCcServerUrl();
        StringBuffer url = new StringBuffer();
        url.append(ccServerUrl);
        url.append("CheckTodayIsOnjob.asmx/CheckTodayIsOnjobInfo");

        return pokeRequestServe.transGet(url.toString(), "非工作日判断接口", "CheckTodayIsOnjob.asmx/CheckTodayIsOnjobInfo");
    }
    @Override
    public ResponseWithData<?> queryPartByFseIdPostCC(PartInfo info) {
        String ccServerUrl = global.getCcServerUrl();
        StringBuffer url = new StringBuffer();
        url.append(ccServerUrl);
        url.append("querypendingPartByFseID.asmx/querypendingPartByFseIDHandle");
        StringBuffer param = new StringBuffer("enginner_id=").append(info.getEnginner_id());
        param.append("&Part_no=").append(info.getPart_no() == null ? "" : info.getPart_no());
        param.append("&Part_name=").append(info.getPart_name() == null ? "" : info.getPart_name());
        return pokeRequestServe.transPost(url.toString(), "获取工程师名下备件接口", "queryPartByFseId", param.toString());
    }
    @Override
    public ResponseWithData<?> queryPartByFseIdPostBg(PartInfo info) {
        String ccServerUrl = global.getCcServerUrl();
        StringBuffer url = new StringBuffer();
        url.append(ccServerUrl);
        url.append("querypendingPartByFseID.asmx/querypendingPartByFseIDHandle");

        StringBuffer param = new StringBuffer("enginner_id=").append(info.getEnginner_id());
       // param.append("&Status=").append(info.getStatus() == null ? "" : info.getStatus());
        param.append("&Part_no=").append(info.getPart_no() == null ? "" : info.getPart_no());
        param.append("&Part_name=").append(info.getPart_name() == null ? "" : info.getPart_name());
        //param.append("&CustName=").append(info.getCustName() == null ? "" : info.getCustName());
       // param.append("&Part_id=").append(info.getPart_id() == null ? "" : info.getPart_id());
       // param.append("&Part_DebitNo=").append(info.getPart_DebitNo() == null ? "" : info.getPart_DebitNo());
       // param.append("&istodo=").append(info.getIstodo() == null ? "" : info.getIstodo());

        ResponseWithData<?> data = pokeRequestServe.transPost(url.toString(), "获取工程师名下备件接口", "queryPartByFseId", param.toString());

        JSONObject obj = JSON.parseObject(data.getData().toString());
        JSONArray jsonArray = obj.getJSONArray("record");
        if(jsonArray==null || jsonArray.size()<=0){
            return data;
        }
        List<StReportPort> rp1 = reportPortMapper.selectUnsubmittedPartQtyCountList(info.getEnginner_id());
        List<StReportPort> rp2 = reportPortMapper.selectUnsubmittedPartQtyCountListByServiceNoAndHelpId(info.getServiceNo(), info.getHelpId(), info.getEnginner_id());
        Map<String,Long> mp = new HashMap<>();
        if(rp1!=null && rp1.size()>0){
            for (int i=0;i<rp1.size();i++){
                mp.put(rp1.get(i).getPartNumber(),rp1.get(i).getQtyCount());
            }
        }
        if(rp2!=null && rp2.size()>0){
            if(mp!=null && mp.size()>0){
                for (int i=0;i<rp2.size();i++){
                    boolean sign = false;
                    for(Map.Entry<String, Long> entry : mp.entrySet()){
                        String mapKey = entry.getKey();
                        if(rp2.get(i).getPartNumber().equals(mapKey)){
                            sign = true;
                            long mapValue = entry.getValue();
                            mp.put(rp2.get(i).getPartNumber(),(rp2.get(i).getQtyCount()+mapValue));
                            break;
                        }
                    }
                    if(!sign){
                        mp.put(rp2.get(i).getPartNumber(),rp2.get(i).getQtyCount());
                    }
                }
            }else{
                for (int i=0;i<rp2.size();i++){
                    mp.put(rp2.get(i).getPartNumber(),rp2.get(i).getQtyCount());
                }
            }
        }

        if(mp==null || mp.size()<=0){
            return data;
        }
        List<String> listNo = new ArrayList<>();

        for(int i=0;i<jsonArray.size();i++){
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            for(Map.Entry<String, Long> entry : mp.entrySet()){
                String mapKey = entry.getKey();
                if(jsonObject.getString("Part_no").equals(mapKey)){
                    // 系统中使用的
                    long mapValue = entry.getValue();
                    // 查询回来的
                    long partQty = jsonObject.getLong("Part_qty");
                    if(partQty > mapValue){
                        jsonObject.put(jsonObject.getString("Part_no"), (partQty - mapValue));
                    }else if(partQty == mapValue){
                        listNo.add(jsonObject.getString("Part_no"));
                    }
                    break;
                }
            }
        }

        if(listNo==null || listNo.size()<=0){
            obj.put("record",jsonArray);
            return new ResponseWithData<>().success(obj.toJSONString()).msg("查询成功").code(200);
        }

        for(int i=0;i<listNo.size();i++){
            for(int j=0;j<jsonArray.size();j++) {
                JSONObject jsonObject = jsonArray.getJSONObject(j);
                if(listNo.get(i).toString().equals(jsonObject.getString("Part_no"))){
                    jsonArray.remove(j);
                    break;
                }
            }
        }
        obj.put("record",jsonArray);
        return new ResponseWithData<>().success(obj.toJSONString()).msg("查询成功").code(200);
    }




}
